//日期格式函数
export function dateFormat(str, typeVal) {
	let oDate = new Date(str);
	let oYear = oDate.getFullYear();
	let oMonth = oDate.getMonth() + 1;
	let oDay = oDate.getDate();
	let oHour = oDate.getHours();
	let oMin = oDate.getMinutes();
	let oSen = oDate.getSeconds();
	if (typeVal == 1) {//月-日
		return getzf(oMonth) + "-" + getzf(oDay);
	}
	if (typeVal == 2) {//时-分
		return getzf(oHour) + ":" + getzf(oMin);
	}
	return oYear + "-" + getzf(oMonth) + "-" + getzf(oDay) + " " + getzf(oHour) + ":" + getzf(oMin) + ":" + getzf(oSen);
};

//补0操作1
function getzf(num) {
	if (parseInt(num) < 10) {
		num = '0' + num;
	}
	return num;
};

//时间差
export function getTimeDifference(date2, type) {
	// console.log(date2);
	let date1 = new Date(); //开始时间
	let date3 = null;
	if (type) {
		date3 = date1.getTime() - date2; // 
	} else {
		date3 = date2 - date1.getTime(); //时间差的毫秒数
	}
	// console.log(date3);
	//计算出小时数 
	let leave1 = date3 % (24 * 3600 * 1000); //计算天数后剩余的毫秒数 
	let hours = Math.floor(leave1 / (3600 * 1000));
	//计算相差分钟数 
	let leave2 = leave1 % (3600 * 1000); //计算小时数后剩余的毫秒数 
	let minutes = Math.floor(leave2 / (60 * 1000));
	//计算相差秒数 
	let leave3 = leave2 % (60 * 1000); //计算分钟数后剩余的毫秒数 
	let seconds = Math.round(leave3 / 1000);
	let Date_data = {
		hour: hours,
		minute: minutes,
		second: seconds,
	};
	return Date_data;
	// return " 相差 " + hours+"小时 "+minutes+" 分钟"+seconds+" 秒"
};

//获取节点信息
export function getdomInfo(node, that) {
	return new Promise((resolve, reject) => {
		try {
			// console.log(node,that);
			const query = uni.createSelectorQuery().in(that);
			that.$nextTick(function() {
				query.select(node).boundingClientRect(data => {
					resolve(data);
				}).exec();
			});
		} catch (e) {
			reject(e);
		}
	});
};

export function copyTxt(txt) { //传入要复制的内容
	txt += "";
	if (txt == "null" || txt == "undefined" || txt == "") {
		//toast("复制失败，内容为空");
		return;
	}
	// #ifdef APP-PLUS
	uni.setClipboardData({
		data: txt,
	});
	// #endif

	// #ifdef H5
	if (document.queryCommandSupported('copy')) {
		let textarea = document.createElement("textarea")
		textarea.value = txt
		textarea.readOnly = "readOnly"
		document.body.appendChild(textarea)
		textarea.select() // 选中文本内容
		textarea.setSelectionRange(0, txt.length)
		let result = document.execCommand("copy")
		textarea.remove()
		uni.showToast({
			title: "复制成功",
			icon: "none",
		})
	} else {
		uni.showToast({
			title: "您的浏览器不支持复制",
			icon: "none"
		})
	}

	// #endif  
};
// 清空剪切板
export function clearCopyTxt() {
	let txt = "";
	// #ifdef APP-PLUS
	uni.setClipboardData({
		data: txt,
	});
	uni.hideToast();
	// #endif

	// #ifdef H5
	if (document.queryCommandSupported('copy')) {
		let textarea = document.createElement("textarea")
		textarea.value = txt
		textarea.readOnly = "readOnly"
		document.body.appendChild(textarea)
		textarea.select() // 选中文本内容
		textarea.setSelectionRange(0, txt.length)
		let result = document.execCommand("copy")
		textarea.remove()
	} else {
		uni.showToast({
			title: "您的浏览器不支持读取剪切板",
			icon: "none"
		})
	}

	// #endif  
};


	//身份证验证
	export const checkIDCard = (idcode) => {
		// 加权因子
		var weight_factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
		// 校验码
		var check_code = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];
	
		var code = idcode + "";
		var last = idcode[17]; //最后一位
	
		var seventeen = code.substring(0, 17);
	
		// ISO 7064:1983.MOD 11-2
		// 判断最后一位校验码是否正确
		var arr = seventeen.split("");
		var len = arr.length;
		var num = 0;
		for (var i = 0; i < len; i++) {
			num = num + arr[i] * weight_factor[i];
		}
	
		// 获取余数
		var resisue = num % 11;
		var last_no = check_code[resisue];
	
		// 格式的正则
		// 正则思路
		/*
		第一位不可能是0
		第二位到第六位可以是0-9
		第七位到第十位是年份，所以七八位为19或者20
		十一位和十二位是月份，这两位是01-12之间的数值
		十三位和十四位是日期，是从01-31之间的数值
		十五，十六，十七都是数字0-9
		十八位可能是数字0-9，也可能是X
		*/
		var idcard_patter =
			/^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;
	
		// 判断格式是否正确
		var format = idcard_patter.test(idcode);
	
		// 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
		return last === last_no && format ? true : false;
	};


//关闭浏览器窗口
export function closeWindow(){
		// #ifdef APP-PLUS
			if (plus.os.name.toLowerCase() === 'android') {
				plus.runtime.quit();
			} else {
				const threadClass = plus.ios.importClass("NSThread");
				const mainThread = plus.ios.invoke(threadClass, "mainThread");
				plus.ios.invoke(mainThread, "exit");
				// ios11
				plus.ios.import("UIApplication").sharedApplication().performSelector("exit")
			}
		// #endif
		
		// #ifdef H5
		setTimeout(() => {
			let browser = navigator.userAgent.toLowerCase();
			if (browser.match(/Alipay/i) == "alipay") {
				console.log("支付宝app的浏览器");
				//这个可以关闭安卓系统的手机
				document.addEventListener("AlipayJSBridgeReady", function() {
						AlipayJSBridge.call("closeWindow");
					},
					false
				);
				//这个可以关闭ios系统的手机
				AlipayJSBridge.call('closeWebview'); //支付宝
			} else if (browser.match(/MicroMessenger/i) == "micromessenger") {
				//这个可以关闭安卓系统的手机
				document.addEventListener("WeixinJSBridgeReady", function() {
						WeixinJSBridge.call("closeWindow");
					},
					false
				);
				//这个可以关闭ios系统的手机
				WeixinJSBridge.call("closeWindow");
			} else {
				console.log("其它浏览器");
				window.opener = null; //如果没有这行和下面的一行则会出现上面的第二个询问框。
				window.open(' ', '_self', ' ');
				window.close()
			}
		}, 2000)
		// #endif
}
//方法：用来判断是否是微信内置的浏览器
export function isWechat(){
	return String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
}

//获取地址参数
export function getUrlCode(name) {
	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) ||
		[, ''
		])[1]
		.replace(/\+/g, '%20')) || null
}

//请求微信接口，用来获取code
export function	getWeChatCode() {
	console.log('getWeChatCode---------------')
	let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址 
	let appid = 'wx40353c84dc668698'

	//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
	window.location.href =
		"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
		appid +
		"&redirect_uri=" +
		local +
		"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
}

//请求支付宝接口，用来获取code
export function getAlipayCode() {
	let local = encodeURIComponent(window.location.href); //获取当前页面地址作为回调地址 
	let appid = '2021003190699828'
	//通过微信官方接口获取code之后，会重新刷新设置的回调地址【redirect_uri】
	window.location.href =
		"https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=" +
		appid +
		"&scope=auth_base&redirect_uri=" +
		local;
}

//获取图片信息
export function getImageInfo(src) {
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
			src: src,
			success: (res) => {
				resolve(res);
			},
			fail: (err) => {
				reject(err);
			}
		});
	});
};
//根据经纬度计算距离
export function distance(lat1, lng1 ,location) {
	if(!lat1 || !lng1)return 0
	if(!location)return 0
	location = JSON.parse(location)
	let lat2 = location.lat;
	let lng2 = location.lng;
	let rad1 = lat1 * Math.PI / 180.0;
	let rad2 = lat2 * Math.PI / 180.0;
	let a = rad1 - rad2;
	let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
	let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) *
		Math.cos(
			rad2) * Math.pow(
			Math.sin(b / 2), 2)));
	s = s * 6378.137;
	s = Math.round(s * 10000) / 10000;
	s = s.toString();
	s = s.substring(0, s.indexOf('.') + 2);
	return s
}

// 分钟差
export function mindiff(day) {
	var newDate = new Date();
	let disparity = newDate.getTime() - Number(day);
	// 转为分钟数的时候，可能会出现精度丢失;你需要注意下
	let second = disparity / 1000;
	return second;
};

//format = 'yyyy-MM-dd hh:mm:ss'
export function dateFormatType(date, format) {
    if (date) {
      let map = new Map();
      map.set('M+', date.getMonth() + 1);
      map.set('d+', date.getDate());
      map.set('d+', date.getDate());
      map.set('h+', date.getHours());
      map.set('m+', date.getMinutes());
      map.set('s+', date.getSeconds());
      map.set('q+', Math.floor((date.getMonth() + 3) / 3));
      map.set('S', date.getMilliseconds());
      if (/(y+)/.test(format)) {
        format = format.replace(
          RegExp.$1,
          `${date.getFullYear()}`.substr(4 - RegExp.$1.length)
        );
      }
      for (let [key, value] of map) {
        if (new RegExp(`(${key})`).test(format)) {
          format = format.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? value
              : `00${value}`.substr(`${value}`.length)
          );
        }
      }
    }
    return format;
  }
	
export function delParam(paramKey) {
	        var url = window.location.href;    //页面url
	        var urlParam = window.location.search.substr(1);   //页面参数
	        var beforeUrl = url.substr(0, url.indexOf("?"));   //页面主地址（参数之前地址）
	        var nextUrl = "";
	
	        var arr = new Array();
	        if (urlParam != "") {
	            var urlParamArr = urlParam.split("&"); //将参数按照&符分成数组
	            for (var i = 0; i < urlParamArr.length; i++) {
	                var paramArr = urlParamArr[i].split("="); //将参数键，值拆开
	                //如果键雨要删除的不一致，则加入到参数中
	                if (paramArr[0] != paramKey) {
	                    arr.push(urlParamArr[i]);
	                }
	            }
	        }
	        if (arr.length > 0) {
	            nextUrl = "?" + arr.join("&");
	        }
	        url = beforeUrl + nextUrl;
	        return url;
	    }